package org.shop.controller.user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.shop.entity.User;
import org.shop.service.UserService;
import org.shop.service.impl.UserServiceImpl;
import org.shop.vo.ErrorVO;

/**
 * 处理用户登录 
 * 1.接收请求 
 * 2.处理请求 - 业务对象 - DAO对象 
 * 3.响应请求
 * 
 * 注意： / == http://localhost:8080/项目名称/
 * 
 * @author Administrator
 * 
 */
@WebServlet("/admin/login.do")
public class LoginServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 第一：获取用户提交的数据
		String uname = req.getParameter("username") ;
		String upass = req.getParameter("password") ;
		// 用户文本框中输入的验证码
		String code = req.getParameter("code") ;
		// 系统生成的验证码
		HttpSession session = req.getSession(true);
		String rand = (String)session.getAttribute("rand");
		// String rand = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY) ;
		
		
		
		// 第二：数据的合法性验证
		// 1.验证密码是否符合约定
		String reg = "\\w{5,}" ;
		boolean isPassOK = upass.matches(reg) ;
		if(!isPassOK) {
			ErrorVO error = new ErrorVO("密码至少输入5个字符","login.jsp");
			req.setAttribute("error", error);
			req.getRequestDispatcher("../error.jsp").forward(req, resp);
			return ;
		} 
		
		// 2.验证验证码是否匹配
		if(code==null || "".equals(code.trim())) {
			ErrorVO error = new ErrorVO("验证码不能为空","login.jsp");
			req.setAttribute("error", error);
			req.getRequestDispatcher("../error.jsp").forward(req, resp);
			return ;
		}
		
		if(!code.equalsIgnoreCase(rand)) {
			ErrorVO error = new ErrorVO("验证码不匹配","login.jsp");
			req.setAttribute("error", error);
			req.getRequestDispatcher("../error.jsp").forward(req, resp);
			return ;
		}
		
		
		// 第三：实例化业务对象或DAO对象，进行相关的处理
		UserService userService = new UserServiceImpl();
		User user = userService.login(uname, upass);
		
		// 第四：响应结果
		// 1.登录失败
		if(user==null) {
			ErrorVO error = new ErrorVO("登录失败，错误的帐号或密码","login.jsp");
			req.setAttribute("error", error);
			req.getRequestDispatcher("../error.jsp").forward(req, resp);
			return ;
		}
		
		// 2.登录成功
		session.setAttribute("user", user);
		resp.sendRedirect("index.jsp");
	}

}






